package main

import (
	"github.com/kardianos/service"
	"os/exec"
	"runtime"
	"strings"
	"time"
)

func main() {
	serConf := &service.Config{
		Name:        "RunToDesk",
		DisplayName: "RunToDesk",
		Description: "chenck and run todesk.exe",
	}
	worker := &WorkerSev{}
	s, err := service.New(worker, serConf)
	if err != nil {
		println("create service fail")
		return
	}
	println("主程序启动")
	err2 := s.Run()
	if err2 != nil {
		println("start service fail")
		return
	}
	println("主程序退出")
}

type WorkerSev struct{}

func (w *WorkerSev) Start(s service.Service) error {
	go func() {
		println("RunToDesk start")
		ticker := time.NewTicker(time.Second * 5)
		for range ticker.C {
			if runtime.GOOS == "linux" {
				go checkOnLinux()
			} else if runtime.GOOS == "windows" {
				go checkOnWindows()
			} else {
				println("不支持当前系统")
				time.Sleep(time.Second * 3)
			}
		}
	}()
	return nil
}
func (w *WorkerSev) Stop(s service.Service) error {
	println("RunToDesk stop")
	return nil
}
func checkOnWindows() {
	//C:\Program Files (x86)\ToDesk\ToDesk.exe
	cmd := exec.Command("tasklist")
	res, err := cmd.CombinedOutput()
	if err != nil {
		println("checkOnWindows err", err)
		time.Sleep(time.Second * 5)
		return
	}
	output := string(res)
	isRunning := len(output) > 0 && strings.Contains(output, "ToDesk")
	if !isRunning {
		println("todesk is not running, starting todesk...")
		startCmd := exec.Command("C:\\Program Files (x86)\\ToDesk\\ToDesk.exe")
		startCmd.Start()
	} else {
		println("todesk is running...")
	}
}
func checkOnLinux() {
	for {
		cmd := exec.Command("pgrep", "processName")
		err := cmd.Run()
		if err != nil {
			println("todesk is not running, starting todesk...")
			startCmd := exec.Command("/processPath/processName.dll")
			startCmd.Start()
		}
		time.Sleep(5 * time.Second)
	}
}
